import 'package:flutter/material.dart';
import '../../utils/SnakeGame.dart';

class SnakeHome extends StatefulWidget {
  SnakeHome({Key? key}) : super(key: key);

  @override
  _SnakeHomeState createState() => _SnakeHomeState();
}

class _SnakeHomeState extends State<SnakeHome> {
  ///棋盘
  CheckerBoard _board = CheckerBoard(columns: 20, width: 400, height: 400);

  ///游戏控制器
  GameController? _controller;

  /// 蛇
  Snake? _snake;

  @override
  void initState() {
    super.initState();
    _snake = Snake(_board.getOrigin(), _board.stepWidth);
    _controller = GameController(board: _board, snake: _snake);
  }

  @override
  Widget build(BuildContext context) {
    print('origin is ${_snake?.head.position}');
    return Scaffold(
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Padding(
                child: Text('贪吃蛇游戏'),
                padding: EdgeInsets.only(bottom: 20),
              ),
              Stack(
                children: [
                  //棋盘
                  Positioned(
                    child: CustomPaint(
                      painter: CheckerPainter(20),
                      size: Size(400, 400),
                    ),
                  ),
                  Positioned(
                    left: (_snake as Snake).head.position.x,
                    top: (_snake as Snake).head.position.y,
                    child: Container(
                      height: _board.stepWidth,
                      width: _board.stepWidth,
                      color: Colors.black87,
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

///棋盘Painter
class CheckerPainter extends CustomPainter {
  CheckerPainter(this.columns);

  ///多少列
  final int columns;

  @override
  void paint(Canvas canvas, Size size) {
    double cellWidth = size.width / columns;

    // 绘制背景
    var paint = Paint()
      ..isAntiAlias = true
      ..style = PaintingStyle.fill
      ..color = Colors.yellow[200] as Color;
    canvas.drawRect(Offset.zero & size, paint);

    // 绘制线
    paint
      ..isAntiAlias = true
      ..style = PaintingStyle.stroke
      ..color = Colors.black54
      ..strokeWidth = 1;
    // 竖线
    for (var i = 0; i <= columns; i++) {
      canvas.drawLine(
          Offset(i * cellWidth, 0), Offset(i * cellWidth, size.height), paint);
    }
    // 横线
    for (var i = 0; i <= columns; i++) {
      canvas.drawLine(
          Offset(0, i * cellWidth), Offset(size.height, i * cellWidth), paint);
    }
  }

  @override
  bool shouldRepaint(CheckerPainter oldDelegate) => false;

  @override
  bool shouldRebuildSemantics(CheckerPainter oldDelegate) => false;
}
